package com.wontube.smr.bo.sites.fs.api;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.wontube.client.extension.utils.StringUtils;
import com.wontube.core.pub.AppEnvironment;
import com.wontube.smr.bo.pub.filters.XmlFilterInputStreamReader;






/**
 * @author yuechao
 * 
 *  4shared.com api有webservice 接口，不幸的是他的接口有问题，会产生奇怪的字符，
 *  
 *  因此通过过http请求直接解析，过滤xml非法字符来解决这个问题
 *  
 *  api 请参考 http://www.4shared.com/developer/docs/intro/
 */
public abstract class FSAPI {
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	private final String templateFormat = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" "
			+ "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
			+ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
			+ "<soapenv:Body>"
			+ "{}"
			+ "</soapenv:Body>"
			+ "</soapenv:Envelope>";

	protected Document invoke(String method, String[] args) {
		try {
			Document doc = this.getResponse(method, args);
			return doc;
		} catch (Exception e) {
			this.logger.error(e.toString());
		}

		return null;
	}

	private String getRequestBody(String method, String[] args) {
		String request = "<" + method
				+ " xmlns=\"http://api.soap.shared.pmstation.com/\">";
		for (int i = 0; i < args.length; i++) {
			request += "<arg" + i + " xmlns=\"\">" + args[i] + "</arg" + i + ">";
		}
		request += "</" + method + ">";
		request = StringUtils.format(templateFormat, request);

		return request;
	}

	private Document getResponse(String method, String[] args)
			throws IOException, SAXException, ParserConfigurationException {
		URL uri = new URL("http://api.4shared.com/jax3/DesktopApp");
		HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setRequestMethod("POST");
		conn.setUseCaches(false);
		conn.setRequestProperty("User-Agent", "");
		conn.setRequestProperty("Connection", "keep-alive");
		conn.setInstanceFollowRedirects(true);
		conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
		conn.connect();

		try {
			OutputStreamWriter writer = new OutputStreamWriter(
					conn.getOutputStream(), AppEnvironment.charsetName);
			try {
				String request = this.getRequestBody(method, args);
				writer.write(request);
			} finally {
				writer.close();
			}

			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			XmlFilterInputStreamReader reader = new XmlFilterInputStreamReader(
					conn.getInputStream(), AppEnvironment.charsetName);
			Document doc = builder.parse(new InputSource(reader));
			doc.getDocumentElement().normalize();
			
			return doc;
		} finally {
			conn.disconnect();
		}
	}
}
